package com.hyyt.shopjsp.wxmg.util;

import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import org.dom4j.Element;
import org.tuckey.web.filters.urlrewrite.utils.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;

/**
 * 微信消息响应接口工具类
 */
public class WxResponseInfo {
	/**
	 * 日志
	 */
	public static Log logger = Log.getLog(WxResponseInfo.class);

	/**
	 * 微信接口验证
	 */
	public static boolean checkSignature(HttpServletRequest request,HttpServletResponse response, String TOKEN) {
		try {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String token = TOKEN;
		String[] tmpArr = { token, timestamp, nonce };
		Arrays.sort(tmpArr);
		String tmpStr =ArrayToString(tmpArr);
		tmpStr = SHA1Encode(tmpStr);
		if (tmpStr.equalsIgnoreCase(signature)) {
			return true;
		} else {
			return false;
		}
		} catch (Exception e) {
			logger.error(e);
		}
		return false;
	}
	// 向请求端发送返回数据
	public static void print(HttpServletResponse response,String content) {
		try {
			response.getWriter().print(content);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	// 数组转字符串
	public static String ArrayToString(String[] arr) {
		try {
		StringBuffer bf = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			bf.append(arr[i]);
		}
		return bf.toString();
		} catch (Exception e) {
			logger.error(e);
		}
		return null;
	}

	// sha1加密
	public static String SHA1Encode(String sourceString) {
		String resultString = null;
		try {
			resultString = new String(sourceString);
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			resultString = byte2hexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
			logger.error(ex);
		}
		return resultString;
	}
   //加密算法
	public static final String byte2hexString(byte[] bytes) {
		try {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString().toUpperCase();
		} catch (Exception ex) {
			logger.error(ex);
		}
		return null;
	}

    /**
     * 被动回复消息，自动响应
     */
    public static void wxAutoResponse(HttpServletResponse response,Element root, String msgType) {
        if("text".equals(msgType)){//1被动响应回复文本消息
            String fromUsername = root.elementText("FromUserName");
            String toUsername = root.elementText("ToUserName");
            String keyword = root.elementTextTrim("Content");
            String time = new Date().getTime() + "";
            String textTpl = "<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[%4$s]]></MsgType><Content><![CDATA[%5$s]]></Content></xml>";
            if (null != keyword && !keyword.equals("")) {
                String contentStr = "hello world";
                String resultStr = textTpl.format(textTpl, fromUsername, toUsername, time, msgType, contentStr);
                logger.info("********resultStr 自动响应="+resultStr);
                WxResponseInfo.print(response,resultStr);
            } else {
                WxResponseInfo.print(response,"Input something...");
            }
        }else if("image".equals(msgType)){//2被动响应回复图片消息
            logger.info("********被动响应回复图片消息********");
            //回复消息内容code
        }else if("voice".equals(msgType)){//3被动响应回复语音消息
            logger.info("********被动响应回复语音消息********");
            //回复消息内容code
        }else if("video".equals(msgType)){//4被动响应回复视频消息
            logger.info("********被动响应回复视频消息********");
            //回复消息内容code
        }else if("music".equals(msgType)){//5被动响应回复音乐消息
            logger.info("********被动响应回复图片消息********");
            //回复消息内容code
        }else if("news".equals(msgType)){//6被动响应回复图文消息
            //注意：多条图文消息信息，默认第一个item为大图,注意，如果图文数超过10，则将会无响应
            logger.info("********被动响应回复图片消息********");
            //回复消息内容code
        }
    }

    /**
     * 微信接收消息存储文件路径
     */
    public static String wxMessageFilePath(String messageType){
        String filepath = String.valueOf(RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_UPLOAD_VISIT_ROOT))+"/"+String.valueOf(RedisDataReadUtil.getSysConfig(StringStaticKey.FILE_SYS_WX))+"/"+String.valueOf(RedisDataReadUtil.getSysConfig(messageType));
        return filepath;
    }

}
